package com.centaline.androidsalesblog.rx.database;

import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.events.MineInfoUpdate;
import com.centaline.androidsalesblog.model.databaseobject.EsfEstateDo;
import com.centaline.androidsalesblog.model.databaseobject.FpHistoryDo;
import com.centaline.androidsalesblog.model.databaseobject.NewEstActDo;
import com.centaline.androidsalesblog.model.databaseobject.NewEstDo;
import com.centaline.androidsalesblog.model.databaseobject.PostDo;

import org.greenrobot.eventbus.EventBus;
import org.litepal.crud.DataSupport;

import rx.Observable;
import rx.Subscriber;

/**
 * 足迹数据保存
 * Created by guilin on 16/2/2.
 */
final class FpHistorySaveOnSubscribe implements Observable.OnSubscribe<Void> {

    private final int type;
    private final String resourceId;
    private final DataSupport dataSupport;

    public FpHistorySaveOnSubscribe(int type, String resourceId, DataSupport dataSupport) {
        this.type = type;
        this.resourceId = resourceId;
        this.dataSupport = dataSupport;
    }

    @Override
    public void call(Subscriber<? super Void> subscriber) {
        DataSupport.deleteAll(FpHistoryDo.class, "resourceId = ?", resourceId);
        switch (type) {
            case 0:
            case 1:
                DataSupport.deleteAll(PostDo.class, "postId = ?", resourceId);
                break;
            case 2:
                DataSupport.deleteAll(EsfEstateDo.class, "CestCode = ?", resourceId);
                break;
            case 3:
                DataSupport.deleteAll(NewEstDo.class, "EstExtId = ?", resourceId);
                break;
            case 4:
                DataSupport.deleteAll(NewEstActDo.class, "ActId = ?", resourceId);
                break;
            default:
                break;
        }
        FpHistoryDo fpHistoryDo = new FpHistoryDo();
        fpHistoryDo.setCityCode(AppConstant.CityCode);
        fpHistoryDo.setResourceId(resourceId);
        fpHistoryDo.setType(type);
        fpHistoryDo.setDate(System.currentTimeMillis());
        fpHistoryDo.save();
        dataSupport.save();
        EventBus.getDefault().post(new MineInfoUpdate(0));
        if (!subscriber.isUnsubscribed()) {
            subscriber.onCompleted();
        }
    }
}
